package com.ljkj.blockpay.network.response;

import android.text.TextUtils;

import androidx.annotation.StringRes;

import com.google.gson.JsonSyntaxException;
import com.ljkj.blockpay.BlockApplication;
import com.ljkj.blockpay.R;
import com.ljkj.blockpay.basedata.BuildConfig;
import com.ljkj.blockpay.network.Network;
import com.ljkj.blockpay.util.GlobalContext;
import com.ljkj.blockpay.util.ToggleToActivity;
import com.luck.picture.lib.tools.ToastUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;

import io.reactivex.observers.DisposableSingleObserver;
import retrofit2.HttpException;

public abstract class AbstractDisposableCallBack<T> extends DisposableSingleObserver<T> {

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            onHttpError(((HttpException) e));
        } else if (e instanceof SocketTimeoutException) {
            onTimeOutError(((SocketTimeoutException) e));
        } else if (e instanceof IOException) {
            onIOError(((IOException) e));
        } else if (e instanceof JsonSyntaxException) {
            onFailed(HttpErrorCode.JSON_ERROR, R.string.retry_later);
        } else {
            onFailed(HttpErrorCode.ERROR, R.string.retry_later);
        }
    }

    private void onHttpError(HttpException error) {
        // 当无缓存时okhttp读取cache会抛出异常：retrofit2.adapter.rxjava2.HttpException: HTTP 504 Unsatisfiable Request (only-if-cached)
        int code = error.code();
        if (code == 504) {
            onFailed(HttpErrorCode.ERROR, R.string.retry_later);
            return;
        }

        String message = error.message();
        if (code == HttpErrorCode.SERVER && !BuildConfig.DEBUG) {
            message = "";
        }
        onFailed(String.valueOf(code), message);
    }

    private void onTimeOutError(SocketTimeoutException e) {
        onFailed(HttpErrorCode.ERROR, e.getMessage());
    }

    private void onIOError(IOException e) {
        if (Network.isNetWorkAvailable(BlockApplication.context)) {
            onFailed(HttpErrorCode.OTHER_IO, e.getMessage());
        } else {
            onFailed(HttpErrorCode.NET_ERROR, R.string.network_error);
        }
    }

    protected abstract void onSafeFailed(String code, String msg);

    private void onFailed(String code, @StringRes int messageId) {
//        onFailed(code, GlobalContext.getApplication().getString(messageId));
    }

    protected void onFailed(String code, String msg) {
        if (TextUtils.equals(code, HttpErrorCode.TOKEN_FAILED)) {
            //登录失效，重新登录
            ToastUtils.s(GlobalContext.getAppContext(),msg);
        } else if (TextUtils.equals(code, HttpErrorCode.FREEZE_ACCOUNT)) {
        } else if (TextUtils.equals(code, HttpErrorCode.FREEZE_DEVICE)) {
        } else if (!HttpErrorCode.CUSTOM_ERROR.equals(code)) {

        }

        onSafeFailed(code, msg);
    }
}
